import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //获取博客列表页数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应和请求的格式
        resp.setContentType("application/json; charset=utf8");
        req.setCharacterEncoding("utf8");
        //从响应中获取blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null) { //博客列表页
            //从数据库中获取所有博客
            BlogDao blogDao = new BlogDao();
            List<Blog> blogList = blogDao.selectAll();
            //返回响应
            resp.getWriter().write(objectMapper.writeValueAsString(blogList));
        } else { //博客详情页
            //根据blogId从数据库中取出相应的blog
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    //发布博客
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求格式
        req.setCharacterEncoding("utf8");
        //获取session会话(为了获取userId)
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!");
            return;
        }
        //根据请求获取博客信息，将数据存入数据库中
        Blog blog = new Blog();
        blog.setTitle(req.getParameter("title"));
        blog.setContent(req.getParameter("content"));
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
